package com.test;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.test.person.PersonInfo;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.awt.*;
import java.time.Duration;
import java.util.Set;

public class CookieLoginDemo {
    public static void main(String[] args) throws InterruptedException {
        // 设置ChromeDriver路径（替换为你的实际路径）
        System.setProperty("webdriver.chrome.driver", "D:/selenium/chromedriver-win64/chromedriver.exe");

        // 配置浏览器选项
        ChromeOptions options = new ChromeOptions();
        options.addArguments("--disable-notifications"); // 禁用通知
        options.setExperimentalOption("excludeSwitches", new String[]{"enable-automation"}); // 禁用自动化提示

        // 初始化WebDriver
        WebDriver driver = new ChromeDriver(options);
        driver.manage().window().maximize(); // 最大化窗口

        try {
            // 第一步：打开登录页面
            driver.get("https://zxfw.court.gov.cn/zxfw/#/pagesGrxx/pc/login/index"); // 替换为你的登录页URL
            System.out.println("请在30秒内完成手动登录...");

            //点击律师用户登录TAB
            driver.findElement(By.xpath("/html/body/uni-app/uni-layout/uni-content/uni-main/uni-page/uni-page-wrapper/uni-page-body/uni-view/uni-view[2]/uni-view[2]/uni-view[1]/uni-view[1]/uni-view[2]")).click();
            Thread.sleep(5000);

            //点击密码登录TAB
            driver.findElement(By.xpath("/html/body/uni-app/uni-layout/uni-content/uni-main/uni-page/uni-page-wrapper/uni-page-body/uni-view/uni-view[2]/uni-view[2]/uni-view[1]/uni-view[2]/uni-view[2]")).click();
            Thread.sleep(3000);

            //输入账号
            WebElement targetElement1 = driver.findElement(By.xpath("/html/body/uni-app/uni-layout/uni-content/uni-main/uni-page/uni-page-wrapper/uni-page-body/uni-view/uni-view[2]/uni-view[2]/uni-view[1]/uni-view[3]/uni-view[1]/uni-view/uni-view/uni-input/div/input"));
            targetElement1.sendKeys("18113663108");
            Thread.sleep(3000);
            //输入密码
            driver.findElement(By.xpath("/html/body/uni-app/uni-layout/uni-content/uni-main/uni-page/uni-page-wrapper/uni-page-body/uni-view/uni-view[2]/uni-view[2]/uni-view[1]/uni-view[3]/uni-view[2]/uni-view/uni-view/uni-input/div/input")).sendKeys("zjs12345678");
            Thread.sleep(10000);
            // 第二步：打开登录后的页面
            driver.get("https://zxfw.court.gov.cn/zxfw/#/pages/pc/home/index");
            // 替换为登录后的页面URL
            System.out.println("已跳转到登录后页面");
            Thread.sleep(3000);
            // 在线立案
            WebElement targetElement = locateElement(driver);
            performClick(driver, targetElement);
            System.out.println("在线立案按钮点击成功");
            // 民事一审
            String mslaXpath = "//uni-view[contains(@class, 'fd-children-item') and contains(@class, 'fd-children-blue') and normalize-space()='民事一审']";
            WebElement mslaElement = selectElement(driver,mslaXpath);
            performClick(driver, mslaElement);
            System.out.println("在线点击民事立案成功按钮点击成功");


            String originalWindow = driver.getWindowHandle();

            WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10).getSeconds());
            wait.until(d -> {
                Set<String> handles = d.getWindowHandles();
                return handles.size() > 1; // 等待直到出现至少2个窗口
            });

            Set<String> allHandles = driver.getWindowHandles();
            for(String handle : allHandles) {
                if(!handle.equals(originalWindow)) {
                    driver.switchTo().window(handle);
                    break;
                }
            }
            Thread.sleep(3000);
            // 诉状立案
            String szlaXpath = "//uni-view[@class='fd-item'][.//uni-view[@class='fd-name' and normalize-space()='诉状识别立案']]";
            WebElement szlaElement = selectElement(driver,szlaXpath);
            performClick(driver, szlaElement);
            // 保持浏览器打开（可选）
            Thread.sleep(3000);
            // 省份下拉框
            String sfxlXpath = "//uni-view[contains(@class, 'uni-stat-box')][.//uni-view[contains(@class, 'uni-select__input-text') and normalize-space()='浙江省']]";
            WebElement sfxlElement = selectElement(driver,sfxlXpath);
            performClick(driver, sfxlElement);
            Thread.sleep(3000);
            //todo 假设已获取到身份证号码
            PersonInfo personInfo = performClick("511324199211206498");
            // 省份选择 todo 这里要被省份拼接进去
            String sfxzXpath = "//uni-view[contains(@class, 'uni-select__selector-item')]//span[normalize-space()='四川省']/ancestor::uni-view[1]";
            sfxzXpath = sfxzXpath.replace("四川省", personInfo.getProvince());
            WebElement sfxzElement = selectElement(driver,sfxzXpath);
            performClick(driver, sfxzElement);
            // 市选择 todo 这里需要吧市拼接进去
            Thread.sleep(3000);
            String sqxzXpath = "//uni-view[@class='fd-city-container']/uni-view[contains(@class, 'fd-city-item') and normalize-space()='成都市']";
            sqxzXpath = sqxzXpath.replace("成都市", personInfo.getCity());
            WebElement sqxzElement = selectElement(driver,sqxzXpath);
            performClick(driver, sqxzElement);
            // 法院选择 todo 这里需要把法院拼接进去
            String fyxzXpath = "//uni-view[@class='fd-wsla-checkbox']//uni-label[.//span[contains(., '锦江区人民法院')]]";
            fyxzXpath = fyxzXpath.replace("锦江区", personInfo.getArea());
            WebElement fyxzElement = selectElement(driver,fyxzXpath);
            performClick(driver, fyxzElement);
            Thread.sleep(4000);
            // 选择申请人类型
            String sqrlxXpath = "//uni-label[contains(@class, 'checklist-box')][.//span[normalize-space()='为他人或公司等组织申请']]";
            WebElement sqrlxElement = selectElement(driver,sqrlxXpath);
            performClick(driver, sqrlxElement);
            Thread.sleep(3000);
            // 下一步
            String xybXpath = "//uni-view[contains(@class, 'fd-com-btn-container')]//uni-button[normalize-space()='下一步']";
            WebElement xybElement = selectElement(driver,xybXpath);
            performClick(driver, xybElement);
            Thread.sleep(3000);
            // 立案须知下一步
            String laxzXpath = "//uni-view[@class='fd-com-btn-container']/uni-button[normalize-space()='下一步']";
            WebElement laxzElement = selectElement(driver,laxzXpath);
            performClick(driver, laxzElement);
            Thread.sleep(3000);
            // 常用案件原有
            String cyajyyXpath = "//span[normalize-space()='民间借贷纠纷']/ancestor::uni-label[contains(@class, 'checklist-box')]";
            WebElement cyahyyElement = selectElement(driver,cyajyyXpath);
            performClick(driver, cyahyyElement);
            Thread.sleep(3000);
            // 常用案件原有下一步
            String cyahyyXybXpath = "//uni-button[normalize-space()='下一步']";
            WebElement cyahyyXybElement = selectElement(driver,cyahyyXybXpath);
            performClick(driver, cyahyyXybElement);
            Thread.sleep(4000);
            // 上传起诉状
            // 3. 定义复合 XPath
            String xpath = "//uni-text[contains(@class, 'uni-section__content-title')]" +
                    "[.//span='起诉状']" +
                    "/ancestor::uni-view[contains(@class, 'uni-section')]" +
                    "//uni-view[contains(@class, 'fd-file-container') " +
                    "and contains(@class, 'fd-btn-add')]";
            String filePath = "/Users/duanzc/Downloads/a.pdf";
            uploadFile(driver,xpath,filePath);
            Thread.sleep(1000);

            String dsrsfzXpath = "//uni-text[contains(@class, 'uni-section__content-title')]" +
                    "[.//span='当事人身份证明']" +
                    "/ancestor::uni-view[contains(@class, 'uni-section')]" +
                    "//uni-view[contains(@class, 'fd-file-container') " +
                    "and contains(@class, 'fd-btn-add')]";
//            String filePath = "/Users/duanzc/Downloads/a.pdf";
            uploadFile(driver,dsrsfzXpath,filePath);
            Thread.sleep(1000);

            String wtrXpath = "//uni-text[contains(@class, 'uni-section__content-title')]" +
                    "[.//span='委托代理人委托手续和身份材料']" +
                    "/ancestor::uni-view[contains(@class, 'uni-section')]" +
                    "//uni-view[contains(@class, 'fd-file-container') " +
                    "and contains(@class, 'fd-btn-add')]";
//            String filePath = "/Users/duanzc/Downloads/a.pdf";
            uploadFile(driver,wtrXpath,filePath);
            Thread.sleep(1000);


            String zjmlXpath = "//uni-text[contains(@class, 'uni-section__content-title')]" +
                    "[.//span='证据目录及证据材料']" +
                    "/ancestor::uni-view[contains(@class, 'uni-section')]" +
                    "//uni-view[contains(@class, 'fd-file-container') " +
                    "and contains(@class, 'fd-btn-add')]";
//            String filePath = "/Users/duanzc/Downloads/a.pdf";
            uploadFile(driver,zjmlXpath,filePath);
            Thread.sleep(1000);

            // 送达地址确认书
            String sddzqyspath = "//uni-text[contains(@class, 'uni-section__content-title')]" +
                    "[.//span='送达地址确认书']" +
                    "/ancestor::uni-view[contains(@class, 'uni-section')]" +
                    "//uni-view[contains(@class, 'fd-file-container') " +
                    "and contains(@class, 'fd-btn-add')]";
//            String filePath = "/Users/duanzc/Downloads/a.pdf";
            uploadFile(driver,sddzqyspath,filePath);
            Thread.sleep(1000);


            // 下一步
            String uploadXybXpath = "//uni-button[normalize-space()='下一步']";
            WebElement uploadXybElement = selectElement(driver,uploadXybXpath);
            performClick(driver, uploadXybElement);
            Thread.sleep(4000);


        } catch (AWTException e) {
            throw new RuntimeException(e);
        } finally {
            // 关闭浏览器（如需要保持打开可注释掉）
            //driver.quit();
        }

    }

    private static WebElement locateElement(WebDriver driver) {
        // 主定位策略：data-v属性 + class组合
        String primaryXpath = "//uni-view[@data-v-03dd4d8f and contains(@class, 'fd-current-menu-btn')]";

        // 备用定位策略
        String fallbackXpath = "//uni-view[contains(text(), '在线立案') and contains(@class, 'fd-menu')]";

        try {
            return new WebDriverWait(driver, Duration.ofSeconds(15).getSeconds())
                    .until(d -> {
                        try {
                            WebElement e = d.findElement(By.xpath(primaryXpath));
                            if (isElementReady(e)) return e;
                        } catch (NoSuchElementException ex) {
                            // 尝试备用定位器
                            WebElement fe = d.findElement(By.xpath(fallbackXpath));
                            if (isElementReady(fe)) return fe;
                        }
                        return null;
                    });
        } catch (TimeoutException e) {
            throw new RuntimeException("无法定位元素，请检查页面结构或定位策略");
        }
    }
    private static WebElement mslaElement(WebDriver driver) {
        // 主定位策略：data-v属性 + class组合
        String primaryXpath = "//uni-view[contains(@class, 'fd-children-item') and contains(@class, 'fd-children-blue') and normalize-space()='民事一审']";


        try {
            return new WebDriverWait(driver, Duration.ofSeconds(15).getSeconds())
                    .until(d -> {
                        try {
                            WebElement e = d.findElement(By.xpath(primaryXpath));
                            if (isElementReady(e)) return e;
                        } catch (NoSuchElementException ex) {
                            // 尝试备用定位器

                        }
                        return null;
                    });
        } catch (TimeoutException e) {
            throw new RuntimeException("无法定位元素，请检查页面结构或定位策略");
        }
    }

    private static WebElement szlaElement(WebDriver driver) {
        // 主定位策略：data-v属性 + class组合
        String primaryXpath = "//uni-view[@class='fd-item'][.//uni-view[@class='fd-name' and normalize-space()='诉状识别立案']]";


        try {
            return new WebDriverWait(driver, Duration.ofSeconds(15).getSeconds())
                    .until(d -> {
                        try {
                            WebElement e = d.findElement(By.xpath(primaryXpath));
                            if (isElementReady(e)) return e;
                        } catch (NoSuchElementException ex) {
                            // 尝试备用定位器

                        }
                        return null;
                    });
        } catch (TimeoutException e) {
            throw new RuntimeException("无法定位元素，请检查页面结构或定位策略");
        }
    }

    private static WebElement sfxzElement(WebDriver driver) {
        // 主定位策略：data-v属性 + class组合
        String primaryXpath = "//uni-text[contains(@class, 'uni-icons') and contains(@class, 'uniui-top')]";


        try {
            return new WebDriverWait(driver, Duration.ofSeconds(15).getSeconds())
                    .until(d -> {
                        try {
                            WebElement e = d.findElement(By.xpath(primaryXpath));
                            if (isElementReady(e)) return e;
                        } catch (NoSuchElementException ex) {
                            // 尝试备用定位器

                        }
                        return null;
                    });
        } catch (TimeoutException e) {
            throw new RuntimeException("无法定位元素，请检查页面结构或定位策略");
        }
    }

    /**
     * 选择标签
     * @param driver
     * @param primaryXpath
     * @return
     */
    private static WebElement selectElement(WebDriver driver,String primaryXpath) {
        try {
            return new WebDriverWait(driver, Duration.ofSeconds(15).getSeconds())
                    .until(d -> {
                        try {
                            WebElement e = d.findElement(By.xpath(primaryXpath));
                            if (isElementReady(e)) return e;
                        } catch (NoSuchElementException ex) {
                            // 尝试备用定位器

                        }
                        return null;
                    });
        } catch (TimeoutException e) {
            throw new RuntimeException("无法定位元素，请检查页面结构或定位策略");
        }
    }

    private static boolean isElementReady(WebElement element) {
        return element.isDisplayed() && element.isEnabled() && element.getLocation().y > 0;
    }

    private static void performClick(WebDriver driver, WebElement element) {
        try {
            // 先尝试常规点击
            new Actions(driver)
                    .moveToElement(element)
                    .click()
                    .perform();
        } catch (ElementClickInterceptedException e) {
            // 如果常规点击失败，滚动到视图并重试
            ((JavascriptExecutor) driver).executeScript(
                    "arguments[0].scrollIntoView({behavior: 'smooth', block: 'center'});", element);
            element.click();
        } catch (WebDriverException e) {
            // 使用JavaScript直接点击
            ((JavascriptExecutor) driver).executeScript(
                    "arguments[0].dispatchEvent(new MouseEvent('click', { bubbles: true }));", element);
        }
    }

    private static void uploadFile(WebDriver driver,String xpath,String filePath) throws AWTException {// 点击触发上传的按钮
        WebElement uploadButton = new WebDriverWait(driver, Duration.ofSeconds(10).getSeconds())
                .until(ExpectedConditions.presenceOfElementLocated(By.xpath(xpath)));
        uploadButton.click();

    // 使用 Robot 类处理系统对话框
    //        Robot robot = new Robot();
    //        robot.delay(1000);

    //// 复制文件路径到剪贴板
    //        StringSelection ss = new StringSelection(filePath);
    //        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
    //
    //// 模拟 Ctrl+V 粘贴
    //        robot.keyPress(KeyEvent.VK_CONTROL);
    //        robot.keyPress(KeyEvent.VK_V);
    //        robot.keyRelease(KeyEvent.VK_V);
    //        robot.keyRelease(KeyEvent.VK_CONTROL);
    //
    //// 模拟回车确认
    //        robot.keyPress(KeyEvent.VK_ENTER);
    //        robot.keyRelease(KeyEvent.VK_ENTER);

        // 3. 定位隐藏的input元素并上传文件
        String inputXpath = "//input[@type='file']"; // 根据实际页面结构调整
        WebElement fileInput = new WebDriverWait(driver, Duration.ofSeconds(10).getSeconds())
                .until(ExpectedConditions.presenceOfElementLocated(By.xpath(inputXpath)));
        fileInput.sendKeys(filePath);

    }

    /**
     * 根据身份证获取省市区
     * @param idCard
     */
    private static PersonInfo performClick(String idCard) {
        try (HttpResponse response = HttpUtil.createPost("https://api.asilu.com/idcard/?id=" + idCard)
                .timeout(20000).execute()) {
            PersonInfo personInfo = JSONUtil.toBean(JSONUtil.toJsonStr(response.body()),PersonInfo.class);
            String [] arr = personInfo.getAddr().split(" ");
            if (arr.length==3) {
                personInfo.setProvince(arr[0]);
                personInfo.setCity(arr[1]);
                personInfo.setArea(arr[2]);
            }
            return personInfo;
        } catch (Exception e) {

        }
        return null;
    }

}